<?php

namespace addons\booking\controller;

use addons\booking\model\Comment as CommentModel;
use addons\booking\model\Order;
use think\Db;

class Comment extends Base
{
    protected $noNeedLogin = ['commentList'];

    /**
     * 评论列表
     */
    public function commentList()
    {
        $this->success('', CommentModel::tableList($this->request->param()));
    }


    /**
     * 添加评论
     */
    public function addComment()
    {
        $pid = $this->request->post('pid/d', 0);
        $order_id = $this->request->post('order_id');
        $remark = $this->request->post('remark/a', '', 'trim,xss_clean');
        if (empty($remark) || !is_array($remark)) {
            $this->error('评论内容不能为空');
        }
        $order = Order::where('id', $order_id)->where('status', 'evaluate')->where('user_id', $this->auth->id)->find();
        if (!$order) {
            $this->error('未找到可评论的订单');
        }
        $row = CommentModel::where('user_id', $this->auth->id)->where('orderid', $order->orderid)->find();
        if ($row) {
            $this->error('订单已评论');
        }
        $data = [];
        $goods_ids = [];
        if ($order['type'] == 1) {
            $goods = $order->source;
            $goods_ids = array_column($goods, 'goods_id');
        }
        foreach ($remark as &$item) {
            if ($order['type'] == 0) {
                if ($order->source_id != $item['source_id']) {
                    $this->error('不可越权操作');
                }
            } else {
                if (!in_array($item['source_id'], $goods_ids)) {
                    $this->error('不可越权操作');
                }
            }
            if (empty($item['comment'])) {
                $this->error('评论内容不能为空');
            }else{
                $item["comment"]=sensitive($item["comment"]);
            }
            if (!isset($item['grade'])) {
                $this->error('缺少评分参数');
            }
            $data[$item['source_id']] = array_merge($item, [
                'pid'     => $pid,
                'type'    => $order['type'],
                'orderid' => $order['orderid'],
                'user_id' => $this->auth->id,
            ]);
        }
        Db::startTrans();
        try {
            (new CommentModel())->saveAll($data);
            $order->status = 'finished';
            $order->save();
            //是否有积分
            $config = get_addon_config('booking');
            if ($config['comment_score'] > 0 && $order['type'] == 0) {
                \app\common\model\User::score($config['comment_score'], $this->auth->id, '评论获赠积分');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('添加评论失败');
        }
        $this->success('添加评论成功,等待审核！');
    }
}
